import config from './ssoConfig'

// sso环境信息
const ssoEnv =
  process.env.NODE_ENV === 'development' ? config.sso.dev : config.sso.pro

/**
 * @description 去单点服务器登录
 */
export const toLogin = () => {
  window.location.href = ssoUrl()
}

/**
 * @description 去单点服务器登出
 */
export const toLogout = token => {
  window.location.href = ssoUrl() + '&session_id=' + token
}

/**
 * @description 去单点服务器地址
 */
export const ssoUrl = url => {
  if (!url) {
    url = ssoEnv.REQUEST_SPLICING_SSO_BASE_URL || ''
  }
  let codeCallbackUrl = ssoEnv.REQUEST_SPLICING_SSO_CODE_CALLBACK
  let pageUrl = window.location.href
  if (pageUrl.indexOf('codeCallback') != -1) {
    pageUrl = ssoEnv.REQUEST_LOCALHOST_URL
  } else {
    pageUrl = encodeURIComponent(pageUrl)
  }
  codeCallbackUrl = encodeURIComponent(codeCallbackUrl + pageUrl)
  return url + codeCallbackUrl
}

export const TOKEN_KEY = 'sso_sessionid'

export const USER_KEY = 'sso_user'

export const setToken = token => {
  window.localStorage.setItem(TOKEN_KEY, token)
}

export const getToken = () => {
  const token = window.localStorage.getItem(TOKEN_KEY)
  if (token) {
    return token
  }
  return false
}

export const removeToken = () => {
  window.localStorage.removeItem(TOKEN_KEY)
}

export const setUser = user => {
  window.localStorage.setItem(USER_KEY, JSON.stringify(user))
}

export const getUser = () => {
  const user = window.localStorage.getItem(USER_KEY)
  if (user) return JSON.parse(user)
  else return false
}

export const removeUser = () => {
  window.localStorage.removeItem(USER_KEY)
}
